import express from 'express'
import { ethers } from 'ethers'
import { authenticateToken } from '../middleware/auth.js'
import db, { generateId } from '../db/database.js'
import { generateWalletAddress, getBalance, monitorTransactions, checkAddressTransactions } from '../services/web3.js'
import { initBinanceClient } from '../services/binance.js'
import { USDT_PRECISION, USDT_DECIMALS } from '../config.js'

const router = express.Router()

// 统一转换余额：直接除以 USDT_PRECISION
function normalizeBalance(value, currency = 'USDT') {
  if (value === null || value === undefined) return 0
  if (typeof value !== 'number') {
    value = parseFloat(value)
    if (isNaN(value)) return 0
  }
  
  if (currency === 'USDT') {
    // 所有 USDT 金额都除以 USDT_PRECISION
    return value / USDT_PRECISION
  }
  
  return value
}

// 所有路由需要认证
router.use(authenticateToken)

// 获取余额
router.get('/balance', async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { sync = 'false', chain } = req.query // 是否同步链上余额，链类型

    // 获取用户钱包
    let query = 'SELECT * FROM wallets WHERE user_id = ?'
    const params = [userId]
    if (chain) {
      query += ' AND chain = ?'
      params.push(chain)
    }
    const wallets = db.prepare(query).all(...params)
    
    let totalBalance = 0
    let totalChainBalance = 0
    let todayDeposit = 0
    let todayWithdraw = 0
    const walletDetails = []

    for (const wallet of wallets) {
      // 统一转换数据库余额：数据库存储的是原始值，需要除以 USDT_PRECISION
      // 如果数据库存储的是转换后的值（小于1），则不再转换；如果是原始值（大于等于1），则转换
      let dbBalance = wallet.balance || 0
      if (typeof dbBalance !== 'number') {
        dbBalance = parseFloat(dbBalance) || 0
      }
      // 判断：如果值大于等于1，很可能是原始值，需要转换；否则可能是已经转换的值
      if (dbBalance >= 1) {
        dbBalance = normalizeBalance(dbBalance, wallet.currency)
      }
      totalBalance += dbBalance

      // 如果需要同步，查询链上余额
      let chainBalance = dbBalance
      if (sync === 'true' && wallet.address) {
        try {
          const walletChain = wallet.chain || 'ETH'
          // getBalance 已经使用 USDT_PRECISION 转换，直接使用返回值
          chainBalance = await getBalance(wallet.address, wallet.currency, walletChain)
          totalChainBalance += chainBalance
          
          // 如果链上余额与数据库不一致，更新数据库（存储转换后的值）
          if (Math.abs(chainBalance - dbBalance) > 0.0001) {
            console.log(`🔄 同步余额: ${wallet.currency} 数据库=${dbBalance}, 链上=${chainBalance}`)
            db.prepare('UPDATE wallets SET balance = ?, updated_at = datetime(\'now\') WHERE id = ?').run(chainBalance, wallet.id)
            totalBalance = totalBalance - dbBalance + chainBalance
            dbBalance = chainBalance // 更新后的余额
          }
        } catch (error) {
          console.error(`查询链上余额失败 (${wallet.address}):`, error)
          chainBalance = dbBalance
          totalChainBalance += chainBalance
        }
      } else {
        totalChainBalance += dbBalance
      }

      walletDetails.push({
        currency: wallet.currency,
        chain: wallet.chain || 'ETH',
        address: wallet.address,
        balance: chainBalance,
        dbBalance: dbBalance,
        chainBalance: sync === 'true' ? chainBalance : undefined
      })

      // 计算今日充值（需要转换）
      const today = new Date().toISOString().split('T')[0]
      const deposits = db.prepare(`
        SELECT SUM(amount) as total FROM transactions
        WHERE user_id = ? AND type = 'deposit' AND status = 'confirmed'
        AND date(created_at) = ?
      `).get(userId, today)
      // 确保转换为数字，数据库可能返回字符串或 null
      const depositTotal = deposits?.total ? Number(deposits.total) : 0
      const depositAmount = normalizeBalance(depositTotal, wallet.currency)
      todayDeposit += depositAmount

      // 计算今日提现（需要转换）
      const withdraws = db.prepare(`
        SELECT SUM(amount) as total FROM transactions
        WHERE user_id = ? AND type = 'withdraw' AND status = 'confirmed'
        AND date(created_at) = ?
      `).get(userId, today)
      // 确保转换为数字，数据库可能返回字符串或 null
      const withdrawTotal = withdraws?.total ? Number(withdraws.total) : 0
      const withdrawAmount = normalizeBalance(withdrawTotal, wallet.currency)
      todayWithdraw += withdrawAmount
    }

    res.json({
      code: 200,
      message: '获取成功',
      success: true,
      data: {
        total: totalBalance,
        chainTotal: sync === 'true' ? totalChainBalance : undefined,
        todayDeposit,
        todayWithdraw,
        wallets: walletDetails,
        usdtDecimals: USDT_DECIMALS // 返回 USDT 小数位数
      }
    })
  } catch (error) {
    next(error)
  }
})

// 查询链上余额（实时查询区块链）
router.get('/balance/chain', async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { currency = 'USDT', chain = 'ETH' } = req.query

    // 获取用户钱包
    const wallet = db.prepare('SELECT * FROM wallets WHERE user_id = ? AND currency = ? AND chain = ?').get(userId, currency, chain)

    if (!wallet || !wallet.address) {
      return res.json({
        code: 404,
        message: '钱包不存在',
        success: false,
        data: null
      })
    }

    // 查询链上余额
    const walletChain = wallet.chain || 'ETH'
    // getBalance 已经使用 USDT_PRECISION 转换，直接使用返回值
    const chainBalance = await getBalance(wallet.address, currency, walletChain)
    // 统一转换数据库余额：数据库存储的是原始值，需要除以 USDT_PRECISION
    // 如果数据库存储的是转换后的值（小于1），则不再转换；如果是原始值（大于等于1），则转换
    let dbBalance = wallet.balance || 0
    if (typeof dbBalance !== 'number') {
      dbBalance = parseFloat(dbBalance) || 0
    }
    // 判断：如果值大于等于1，很可能是原始值，需要转换；否则可能是已经转换的值
    if (dbBalance >= 1) {
      dbBalance = normalizeBalance(dbBalance, currency)
    }

    // 调试：打印原始数据
    console.log(`🔍 [查询链上余额] 用户: ${userId}, 币种: ${currency}, 链: ${walletChain}`)
    console.log(`   链上余额: ${chainBalance}, 类型: ${typeof chainBalance}`)
    console.log(`   数据库余额 (转换后): ${dbBalance}, 类型: ${typeof dbBalance}`)

    // 如果链上余额与数据库不一致，更新数据库（存储转换后的值）
    if (Math.abs(chainBalance - dbBalance) > 0.0001) {
      console.log(`🔄 同步余额: ${currency} 数据库=${dbBalance}, 链上=${chainBalance}`)
      db.prepare('UPDATE wallets SET balance = ?, updated_at = datetime(\'now\') WHERE id = ?').run(chainBalance, wallet.id)
      dbBalance = chainBalance // 更新后的余额
    }

    console.log(`   最终返回: chainBalance=${chainBalance}, dbBalance=${dbBalance}`)

    res.json({
      code: 200,
      message: '查询成功',
      success: true,
      data: {
        currency,
        chain: walletChain,
        address: wallet.address,
        chainBalance, // 链上余额
        dbBalance,    // 数据库余额（已转换）
        synced: Math.abs(chainBalance - dbBalance) <= 0.0001,
        usdtDecimals: USDT_DECIMALS // 返回 USDT 小数位数
      }
    })
  } catch (error) {
    console.error('查询链上余额失败:', error)
    res.json({
      code: 500,
      message: '查询链上余额失败: ' + error.message,
      success: false,
      data: null
    })
  }
})

// 获取钱包地址
router.get('/address/:currency', async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { currency } = req.params
    const { chain = 'ETH' } = req.query

    // 查找或创建钱包
    let wallet = db.prepare('SELECT * FROM wallets WHERE user_id = ? AND currency = ? AND chain = ?').get(userId, currency, chain)

    if (!wallet) {
      // 生成新钱包
      const walletData = await generateWalletAddress(currency)
      const walletId = generateId()

      db.prepare(`
        INSERT INTO wallets (id, user_id, currency, chain, address, private_key_encrypted, balance)
        VALUES (?, ?, ?, ?, ?, ?, 0)
      `).run(walletId, userId, currency, chain, walletData.address, walletData.encryptedPrivateKey)

      wallet = db.prepare('SELECT * FROM wallets WHERE id = ?').get(walletId)

      // 开始监控这个地址的交易
      monitorTransactions(walletData.address, userId, currency, chain)
    }

    res.json({
      code: 200,
      message: '获取成功',
      success: true,
      data: {
        address: wallet.address,
        currency: wallet.currency,
        chain: wallet.chain || 'ETH'
      }
    })
  } catch (error) {
    next(error)
  }
})

// 生成充值地址
router.post('/deposit-address', async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { currency = 'USDT', chain = 'ETH' } = req.body

    // 获取或创建钱包
    let wallet = db.prepare('SELECT * FROM wallets WHERE user_id = ? AND currency = ? AND chain = ?').get(userId, currency, chain)

    if (!wallet) {
      // 生成新钱包
      const walletData = await generateWalletAddress(currency)
      const walletId = generateId()

      db.prepare(`
        INSERT INTO wallets (id, user_id, currency, chain, address, private_key_encrypted, balance)
        VALUES (?, ?, ?, ?, ?, ?, 0)
      `).run(walletId, userId, currency, chain, walletData.address, walletData.encryptedPrivateKey)

      wallet = db.prepare('SELECT * FROM wallets WHERE id = ?').get(walletId)

      // 记录充值地址
      const depositAddressId = generateId()
      db.prepare(`
        INSERT INTO deposit_addresses (id, user_id, currency, address, status)
        VALUES (?, ?, ?, ?, 'active')
      `).run(depositAddressId, userId, currency, wallet.address)
    }

    // 确保开始监控这个地址的交易（无论是否是新钱包）
    monitorTransactions(wallet.address, userId, currency, chain)

    res.json({
      code: 200,
      message: '生成成功',
      success: true,
      data: {
        address: wallet.address,
        currency: wallet.currency,
        chain: wallet.chain || 'ETH'
      }
    })
  } catch (error) {
    next(error)
  }
})

// 转账
router.post('/transfer', async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { to, amount, currency = 'USDT', memo } = req.body

    if (!to || !amount || amount <= 0) {
      return res.status(400).json({
        code: 400,
        message: '请提供有效的收款地址和金额',
        success: false
      })
    }

    // 获取用户钱包
    const wallet = db.prepare('SELECT * FROM wallets WHERE user_id = ? AND currency = ?').get(userId, currency)
    if (!wallet) {
      return res.status(404).json({
        code: 404,
        message: '钱包不存在',
        success: false
      })
    }

    // 统一转换数据库余额（如果存储的是原始值）
    const dbBalance = normalizeBalance(wallet.balance || 0, currency)
    
    // 检查余额（用户输入的 amount 是转换后的值）
    if (dbBalance < amount) {
      return res.status(400).json({
        code: 400,
        message: '余额不足',
        success: false
      })
    }

    // 创建交易记录
    const txId = generateId()
    db.prepare(`
      INSERT INTO transactions (id, tx_id, user_id, type, currency, amount, from_address, to_address, status, memo)
      VALUES (?, ?, ?, 'transfer', ?, ?, ?, ?, 'pending', ?)
    `).run(txId, txId, userId, currency, amount, wallet.address, to, memo || null)

    // 更新余额（先扣除，等待确认）
    // 使用转换后的余额减去标准值，然后存储标准值
    const newBalance = dbBalance - amount
    db.prepare('UPDATE wallets SET balance = ? WHERE id = ?').run(newBalance, wallet.id)

    // TODO: 实际发送区块链交易
    // 这里需要调用Web3服务发送交易

    res.json({
      code: 200,
      message: '转账已提交',
      success: true,
      data: {
        txId,
        status: 'pending'
      }
    })
  } catch (error) {
    next(error)
  }
})

// 提现
router.post('/withdraw', async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { to, amount, currency = 'USDT', memo } = req.body

    if (!to || !amount || amount <= 0) {
      return res.status(400).json({
        code: 400,
        message: '请提供有效的提现地址和金额',
        success: false
      })
    }

    // 获取用户钱包
    const wallet = db.prepare('SELECT * FROM wallets WHERE user_id = ? AND currency = ?').get(userId, currency)
    if (!wallet) {
      return res.status(404).json({
        code: 404,
        message: '钱包不存在',
        success: false
      })
    }

    // 统一转换数据库余额（如果存储的是原始值）
    const dbBalance = normalizeBalance(wallet.balance || 0, currency)
    
    // 检查余额（包含手续费，用户输入的 amount 是转换后的值）
    const fee = 0.001 // 手续费
    if (dbBalance < amount + fee) {
      return res.status(400).json({
        code: 400,
        message: '余额不足（包含手续费）',
        success: false
      })
    }

    // 创建交易记录
    const txId = generateId()
    db.prepare(`
      INSERT INTO transactions (id, tx_id, user_id, type, currency, amount, from_address, to_address, status, memo)
      VALUES (?, ?, ?, 'withdraw', ?, ?, ?, ?, 'pending', ?)
    `).run(txId, txId, userId, currency, amount, wallet.address, to, memo || null)

    // 更新余额（先扣除，等待确认）
    // 使用转换后的余额减去标准值，然后存储标准值
    const newBalance = dbBalance - amount - fee
    db.prepare('UPDATE wallets SET balance = ? WHERE id = ?').run(newBalance, wallet.id)

    // TODO: 实际发送区块链交易或通过币安API提现
    // 这里需要调用币安API或Web3服务发送交易

    res.json({
      code: 200,
      message: '提现申请已提交',
      success: true,
      data: {
        txId,
        status: 'pending'
      }
    })
  } catch (error) {
    next(error)
  }
})

// 获取交易记录
router.get('/transactions', async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { page = 1, pageSize = 10, type, currency } = req.query

    let query = 'SELECT * FROM transactions WHERE user_id = ?'
    const params = [userId]

    if (type) {
      query += ' AND type = ?'
      params.push(type)
    }

    if (currency) {
      query += ' AND currency = ?'
      params.push(currency)
    }

    query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?'
    params.push(parseInt(pageSize), (parseInt(page) - 1) * parseInt(pageSize))

    const transactions = db.prepare(query).all(...params)

    // 格式化交易记录（统一转换金额）
    const formattedTransactions = transactions.map(tx => ({
      txId: tx.tx_id,
      type: tx.type,
      amount: normalizeBalance(tx.amount || 0, tx.currency || 'USDT'), // 统一转换金额
      currency: tx.currency,
      from: tx.from_address,
      to: tx.to_address,
      status: tx.status,
      memo: tx.memo,
      createdAt: tx.created_at,
      blockNumber: tx.block_number,
      confirmations: tx.confirmations
    }))

    // 获取总数
    let countQuery = 'SELECT COUNT(*) as total FROM transactions WHERE user_id = ?'
    const countParams = [userId]

    if (type) {
      countQuery += ' AND type = ?'
      countParams.push(type)
    }

    if (currency) {
      countQuery += ' AND currency = ?'
      countParams.push(currency)
    }

    const total = db.prepare(countQuery).get(...countParams).total

    res.json({
      code: 200,
      message: '获取成功',
      success: true,
      data: {
        list: formattedTransactions,
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    })
  } catch (error) {
    next(error)
  }
})

// 获取交易详情
router.get('/transactions/:txId', async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { txId } = req.params

    const transaction = db.prepare('SELECT * FROM transactions WHERE tx_id = ? AND user_id = ?').get(txId, userId)

    if (!transaction) {
      return res.status(404).json({
        code: 404,
        message: '交易不存在',
        success: false
      })
    }

    const formattedTransaction = {
      txId: transaction.tx_id,
      type: transaction.type,
      amount: normalizeBalance(transaction.amount || 0, transaction.currency || 'USDT'), // 统一转换金额
      currency: transaction.currency,
      from: transaction.from_address,
      to: transaction.to_address,
      status: transaction.status,
      memo: transaction.memo,
      createdAt: transaction.created_at,
      blockNumber: transaction.block_number,
      confirmations: transaction.confirmations
    }

    res.json({
      code: 200,
      message: '获取成功',
      success: true,
      data: formattedTransaction
    })
  } catch (error) {
    next(error)
  }
})

// 手动触发充值检查（用于测试和立即检查）
router.post('/check-deposit', async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { currency = 'USDT', chain = 'ETH' } = req.body

    // 获取用户钱包
    const wallet = db.prepare('SELECT * FROM wallets WHERE user_id = ? AND currency = ? AND chain = ?').get(userId, currency, chain)
    if (!wallet) {
      return res.status(404).json({
        code: 404,
        message: '钱包不存在',
        success: false
      })
    }

    console.log(`\n🔍 [手动检查] 用户 ${userId} 请求检查充值地址: ${wallet.address}`)

    // 确保地址在监控列表中
    const walletChain = wallet.chain || 'ETH'
    monitorTransactions(wallet.address, userId, currency, walletChain)

    // 查询链上余额
    let chainBalance = 0
    try {
      // getBalance 已经使用 USDT_PRECISION 转换，直接使用返回值
      chainBalance = await getBalance(wallet.address, currency, walletChain)
      console.log(`   链上余额: ${chainBalance} ${currency} (${walletChain})`)
    } catch (error) {
      console.error(`   查询链上余额失败:`, error)
    }

    // 立即检查交易
    await checkAddressTransactions(wallet.address, userId, currency, walletChain)

    // 获取最新的余额
    const updatedWallet = db.prepare('SELECT * FROM wallets WHERE id = ?').get(wallet.id)
    
    // 统一转换数据库余额（如果存储的是原始值）
    const dbBalance = normalizeBalance(updatedWallet.balance || 0, currency)
    
    // 获取所有充值交易记录
    const allDepositTransactions = db.prepare(`
      SELECT * FROM transactions 
      WHERE user_id = ? AND currency = ? AND type = 'deposit'
      ORDER BY created_at DESC
    `).all(userId, currency)

    // 获取最近的5笔交易
    const recentTransactions = allDepositTransactions.slice(0, 5)

    // 计算总充值金额（需要转换）
    const totalDeposit = allDepositTransactions.reduce((sum, tx) => {
      const amount = normalizeBalance(tx.amount || 0, currency)
      return sum + amount
    }, 0)

    res.json({
      code: 200,
      message: '检查完成',
      success: true,
      data: {
        address: wallet.address,
        chain: walletChain,
        checked: true,
        chainBalance, // 链上余额（已转换）
        dbBalance, // 数据库余额（已转换）
        synced: Math.abs(chainBalance - dbBalance) <= 0.0001, // 是否同步
        totalDeposit, // 总充值金额（已转换）
        transactionCount: allDepositTransactions.length, // 交易总数
        usdtDecimals: USDT_DECIMALS, // 返回 USDT 小数位数
        recentTransactions: recentTransactions.map(tx => ({
          id: tx.id,
          txId: tx.tx_id,
          amount: normalizeBalance(tx.amount || 0, currency), // 统一转换金额
          fromAddress: tx.from_address,
          toAddress: tx.to_address,
          status: tx.status,
          blockNumber: tx.block_number,
          createdAt: tx.created_at
        })),
        allTransactions: allDepositTransactions.map(tx => ({
          id: tx.id,
          txId: tx.tx_id,
          amount: tx.amount,
          fromAddress: tx.from_address,
          toAddress: tx.to_address,
          status: tx.status,
          blockNumber: tx.block_number,
          createdAt: tx.created_at
        }))
      }
    })
  } catch (error) {
    console.error('手动检查充值失败:', error)
    next(error)
  }
})

// 调试接口：查看所有交易记录（包括详细信息）
router.get('/debug/transactions', async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { currency, type } = req.query

    let query = 'SELECT * FROM transactions WHERE user_id = ?'
    const params = [userId]

    if (currency) {
      query += ' AND currency = ?'
      params.push(currency)
    }

    if (type) {
      query += ' AND type = ?'
      params.push(type)
    }

    query += ' ORDER BY created_at DESC'

    const transactions = db.prepare(query).all(...params)

    // 获取钱包信息
    const wallets = db.prepare('SELECT * FROM wallets WHERE user_id = ?').all(userId)

    res.json({
      code: 200,
      message: '查询成功',
      success: true,
      data: {
        total: transactions.length,
        wallets: wallets.map(w => ({
          currency: w.currency,
          address: w.address,
          balance: w.balance
        })),
        transactions: transactions.map(tx => ({
          id: tx.id,
          txId: tx.tx_id,
          type: tx.type,
          currency: tx.currency,
          amount: tx.amount,
          fromAddress: tx.from_address,
          toAddress: tx.to_address,
          status: tx.status,
          blockNumber: tx.block_number,
          memo: tx.memo,
          createdAt: tx.created_at,
          updatedAt: tx.updated_at
        }))
      }
    })
  } catch (error) {
    console.error('查询交易记录失败:', error)
    next(error)
  }
})

export default router

